<template>
  <el-drawer
    :title="t('resource.resourceTree')"
    :model-value="state.dialogFormVisible"
    :before-close="handleClose"
    size="40%"
    direction="rtl"
  >
    <template #default>
      <el-tree
        v-if="state.refresh"
        node-key="resourceId"
        :props="treeProps"
        :load="lazyLoadNode"
        lazy
      />
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import apiResource from "../api/resource";
import ResourceTreeNode from "./tree-node";
import Node from "element-plus/es/components/tree/src/model/node";
import { useI18n } from "vue-i18n";
const { t } = useI18n({ useScope: "global" });
const treeProps = {
  label: "resourceName",
  children: "children",
  isLeaf: "leaf",
};

const state = reactive({
  dialogFormVisible: false,
  refresh: true,
});

const handleClose = (submit: boolean) => {
  state.dialogFormVisible = false;
  state.refresh = false;
};

const show = () => {
  // 触发刷新树
  state.refresh = true;
  state.dialogFormVisible = true;
};

const lazyLoadNode = async (
  node: Node,
  resolve: (data: ResourceTreeNode[]) => void
) => {
  if (node.level === 0) {
    let treeData = await apiResource.loadChilds("0");
    return resolve(treeData);
  } else {
    if (node.data.leaf) {
      resolve([]);
    }
    let treeData = await apiResource.loadChilds(node.data.resourceId);
    return resolve(treeData);
  }
};

defineExpose({
  show,
});
</script>
